<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属机构" prop="institutionId">
        <el-select v-model="queryParams.institutionId" placeholder="请选择机构" style="width: 140px;" clearable>
          <el-option v-for="dict in institutions" :key="dict.id" :label="dict.institutionname" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="医生团队" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择团队" style="width: 120px;" clearable>
          <el-option v-for="dict in teams" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务包" prop="packageId">
        <el-select v-model="queryParams.packageId" placeholder="请选择服务包" style="width: 150px;" clearable>
          <el-option v-for="dict in package_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择服务状态" style="width: 150px;" clearable>
          <template v-for="dict in audit_tatus_five">
            <el-option v-if="dict.value >= 3" :key="dict.value" :label="dict.label" :value="dict.value">
            </el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="预约时间" prop="appointmentTime">
        <el-date-picker clearable v-model="queryParams.appointmentTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择预约时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['service_record:service_record:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['service_record:service_record:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['service_record:service_record:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['service_record:service_record:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="service_recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="服务编号" align="center" prop="id" /> -->
      <el-table-column label="居民编号" align="center" prop="userId">
        <template #default="scope">
          <span v-for="user in users">
            <span v-if="user.id == scope.row.userId">
              {{ user.id }}
            </span>
          </span>
        </template>
      </el-table-column>
      <!-- 居民姓名  居民身份证 居民电话-->
      <el-table-column label="居民姓名" align="center" prop="userId">
        <template #default="scope">
          <span v-for="user in users">
            <span v-if="user.id == scope.row.userId">
              {{ user.name }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="身份证号" align="center" prop="userId">
        <template #default="scope">
          <span v-for="user in users">
            <span v-if="user.id == scope.row.userId">
              {{ user.idcard }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="居民电话" align="center" prop="userId">
        <template #default="scope">
          <span v-for="user in users">
            <span v-if="user.id == scope.row.userId">
              {{ user.tel }}
            </span>
          </span>
        </template>
      </el-table-column>

      <el-table-column label="医生名称" align="center" prop="doctorId">
        <template #default="scope">
          <!-- <dict-tag :options="years" :value="scope.row.doctorId"/> -->
          <span v-for="dc in doctors">
            <span v-if="dc.id == scope.row.doctorId">
              {{ dc.name }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="服务包" align="center" prop="packageId">
        <template #default="scope">
          <dict-tag :options="package_type" :value="scope.row.packageId" />
        </template>
      </el-table-column>
      <el-table-column label="服务状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="audit_tatus_five" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="提交时间" align="center" prop="submissionTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.submissionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="取消时间" align="center" prop="cancellationTime" /> -->
      <el-table-column label="操作" align="center" width="300px" fixed="right" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Shenhe" @click="handleshenhe(scope.row)">审核</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['service_record:service_record:edit']">修改</el-button>
          <el-button link type="primary" icon="Document" @click="handleDetail(scope.row)"
            v-hasPermi="['service_record:service_record:detail']">详情</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['service_record:service_record:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改服务记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="service_recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="居民姓名" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择居民姓名">
            <el-option v-for="user in users" :key="user.id" :label="user.name" :value="user.id"></el-option>
          </el-select>
          <!-- <el-input v-model="form.userId" placeholder="请输入居民id(外键)" /> -->
        </el-form-item>
        <el-form-item label="机构名称" prop="institutionId">
          <el-select v-model="form.organizationId" placeholder="请选择机构">
            <el-option v-for="dict in institutions" :key="dict.id" :label="dict.institutionname"
              :value="parseInt(dict.id)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="团队名称" prop="teamId">
          <el-select v-model="form.teamId" placeholder="请选择团队外键">
            <el-option v-for="dict in teams" :key="dict.id" :label="dict.name" :value="parseInt(dict.id)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医生名称" prop="doctorId">
          <el-select v-model="form.doctorId" placeholder="请选择医生名称">
            <el-option v-for="dict in doctors" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务包" prop="packageId">
          <el-select v-model="form.packageId" placeholder="请选择服务包">
            <el-option v-for="dict in package_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务项目" prop="itemId">
          <el-select v-model="form.itemId" placeholder="请选择服务项目">
            <el-option v-for="dict in service_items" :key="dict.itemId" :label="dict.itemName"
              :value="parseInt(dict.itemId)">
            </el-option>
          </el-select>
          <!-- <el-input v-model="form.itemId" placeholder="请输入服务项目(外键)" /> -->
        </el-form-item>
        <el-form-item label="服务状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择服务状态">
            <template v-for="dict in audit_tatus_five">
              <el-option v-if="dict.value >= 3" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)">
              </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="服务地点" prop="location">
          <el-select v-model="form.location" placeholder="请选择服务地点">
            <el-option v-for="dict in service_locations" :key="dict.value" :label="dict.label"
              :value=dict.value></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker clearable v-model="form.appointmentTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="提交时间" prop="submissionTime">
          <el-date-picker clearable v-model="form.submissionTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择提交时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核时间" prop="auditTime">
          <el-date-picker clearable v-model="form.auditTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择审核时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核人" prop="auditorId">
          <el-input v-model="form.auditorId" placeholder="请输入审核人id" readonly>
            {{ state.user.userName }}
          </el-input>
        </el-form-item>
        <el-form-item label="取消原因" prop="cancellationReason">
          <el-input v-model="form.cancellationReason" placeholder="请输入取消原因" />
        </el-form-item>
        <el-form-item label="完成时间" prop="finishTime">
          <el-date-picker clearable v-model="form.finishTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="服务备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入服务备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加审核弹出框 -->
    <el-dialog title="审核判断" v-model="auditDialogVisible" width="500px" append-to-body>
      <p>是否审核该记录？</p>
      <template #footer>
        <el-button type="primary" @click="approveAudit">审核通过</el-button>
        <el-button type="danger" @click="rejectAudit">驳回</el-button>
        <el-button type="success" @click="completeAudit">已完成</el-button>
        <el-button @click="cancelAudit">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Service_record">
import { listService_record, getService_record, delService_record, addService_record, updateService_record } from "@/api/service_record/service_record";
import { useRouter } from "vue-router";
import { listDoctor } from "@/api/system/doctor";
import { listResident } from "@/api/resident/resident";
import { listInstitution } from "@/api/system/institution";
import { listItem } from "@/api/item/item";
import { listTeam } from "@/api/system/team";

import { getUserProfile } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const { years, audit_tatus_five, package_type, service_locations } = proxy.useDict('years', 'audit_tatus_five', 'package_type', 'service_locations');

const service_recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
//  用户信息
const state = reactive({
  user: {},
  roleGroup: {},
  postGroup: {}
});
function getUser() {
  getUserProfile().then(response => {
    state.user = response.data;
    console.log(state.user);
    state.roleGroup = response.roleGroup;
    state.postGroup = response.postGroup;
  });
};

getUser();

// 定义一个service_items数组，用于存储服务项目数据
const service_items = ref([]);
// 定义一个方法、动态获取服务项目数据
function getService_items() {
  listItem().then(response => {
    service_items.value = response.rows;
    console.log(service_items.value);
  });
}
// 调用getService_items方法，获取服务项目数据
getService_items();

// 定义一个institutions数组，用于存储机构数据
const institutions = ref([]);
// 定义一个方法、动态获取机构数据
function getInstitutions() {
  listInstitution().then(response => {
    institutions.value = response.rows;
    // console.log(institutions.value);
  });

}
// 调用getInstitutions方法，获取机构数据
getInstitutions();

// 定义一个teams数组，用于存储团队数据
const teams = ref([]);
// 定义一个方法、动态获取团队数据
function getTeams() {
  listTeam().then(response => {
    teams.value = response.rows;
    console.log(teams.value);
  });
}
// 调用getTeams方法，获取团队数据
getTeams();


// 定义一个users数组，用于存储用户数据
const users = ref([]);
// 定义一个方法、动态获取用户数据
function getUsers() {
  listResident().then(response => {
    users.value = response.rows;
    console.log(users.value);
  });
}
// 调用getUsers方法，获取用户数据
getUsers();

// 定义一个doctors数组，用于存储医生数据
const doctors = ref([]);
// 定义一个方法、动态获取医生数据
function getDoctors() {
  listDoctor().then(response => {
    doctors.value = response.rows;
    // console.log(doctors.value);
  });
}
// 调用getDoctors方法，获取医生数据
getDoctors();
// 详情页跳转
const router = useRouter();
const handleDetail = (row) => {
  const ids = row.id;
  router.push({ path: 'servicexiangqing', query: { id: ids } });
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    teamId: null,
    packageId: null,
    status: null,
    appointmentTime: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询服务记录列表 */
function getList() {
  loading.value = true;
  listService_record(queryParams.value).then(response => {
    // 过滤服务状态大于 2 的记录
    service_recordList.value = response.rows.filter(item => item.status === 3 || item.status === 4 || item.status === 5);
    // 更新 total 为过滤后的记录数
    total.value = service_recordList.value.length;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    organizationId: null,
    teamId: null,
    doctorId: null,
    packageId: null,
    itemId: null,
    status: null,
    location: null,
    appointmentTime: null,
    submissionTime: null,
    auditTime: null,
    auditorId: state.user.userName,
    cancellationTime: null,
    cancellationReason: null,
    finishTime: null,
    remark: null
  };
  proxy.resetForm("service_recordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加服务记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getService_record(_id).then(response => {
    form.value = response.data;
    // 手动更新审核人
    form.value.auditorId = state.user.userName;
    open.value = true;
    title.value = "修改服务记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["service_recordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateService_record(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addService_record(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除服务记录编号为"' + _ids + '"的数据项？').then(function () {
    return delService_record(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service_record/service_record/export', {
    ...queryParams.value
  }, `service_record_${new Date().getTime()}.xlsx`)
}


// 新增控制审核弹出框显示的变量
const auditDialogVisible = ref(false);
  // 新增存储当前审核记录的变量
  const currentAuditRecord = ref({});

  // 审核按钮操作
  function handleshenhe(row) {
    currentAuditRecord.value = row;
    auditDialogVisible.value = true;
  }

  // 审核通过按钮点击方法
  function approveAudit() {
    const recordId = currentAuditRecord.value.id;
    const updatedRecord = {
      id: recordId,
      status: 5 // 待服务状态值为5
    };
    updateService_record(updatedRecord).then(() => {
      proxy.$modal.msgSuccess("审核通过，状态已更新为待服务");
      auditDialogVisible.value = false;
      getList();
    }).catch(() => {
      proxy.$modal.msgError("审核通过操作失败");
    });
  }

  // 驳回按钮点击方法
  function rejectAudit() {
    const recordId = currentAuditRecord.value.id;
    const updatedRecord = {
      id: recordId,
      status: 4 // 已驳回状态值为4
    };
    updateService_record(updatedRecord).then(() => {
      proxy.$modal.msgSuccess("已驳回，状态已更新为已驳回");
      auditDialogVisible.value = false;
      getList();
    }).catch(() => {
      proxy.$modal.msgError("驳回操作失败");
    });
  }

  // 已完成按钮点击方法
  function completeAudit() {
    const recordId = currentAuditRecord.value.id;
    const updatedRecord = {
      id: recordId,
      status: 1 // 已完成状态值为1
    };
    updateService_record(updatedRecord).then(() => {
      proxy.$modal.msgSuccess("已完成，状态已更新为已完成");
      auditDialogVisible.value = false;
      getList();
    }).catch(() => {
      proxy.$modal.msgError("已完成操作失败");
    });
  }

  // 取消按钮点击方法
  function cancelAudit() {
    auditDialogVisible.value = false;
  }


getList();
</script>
